

import GameData_blxf from "../GameData/GameData";
import { BaseTargetData_blxf } from "../GameData/TargetData";
import { CsvManager_blxf } from "../Manager/CsvManager";
import { EnumManager_blxf } from "../Manager/EnumManager";
import PageManager_blxf from "../Manager/PageManager";
import AudioModule_blxf from "../Module/AudioModule";
import { ConfigModule_blxf } from "../Module/ConfigModule";
import { LoadModule_blxf } from "../Module/LoadModule";
import { NumModule_blxf } from "../Module/NumModule";
import { UtilsModule_blxf } from "../Module/UtilsModule";
import GuestItem_blxf from "./guestItem";
import TargetItem_blxf from "./targetItem";

const {ccclass, property} = cc._decorator;

@ccclass
export default class AutoSalePanel_blxf extends cc.Component {
    @property({ type: cc.Node, tooltip: '背景图' })
    bgNode: cc.Node = null;

    @property({ type: cc.Node, tooltip: '小卖部盒子' })
    nameBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: 'ui盒子' })
    uiBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: '摊位ui盒子' })
    vendorUIBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: '摊位UIitem' })
    vendorUIItem: cc.Node = null;

    @property({ type: cc.Prefab, tooltip: '菜摊item' })
    vendorItem: cc.Prefab = null;

    @property({ type: cc.Node, tooltip: '摊位盒子' })
    vendorBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: '菜篮子盒子' })
    targetBox: cc.Node = null;

    @property({ type: cc.Prefab, tooltip: '菜篮子预制体' })
    targetItem: cc.Prefab = null;

    @property({ type: cc.Node, tooltip: '客人盒子' })
    guestBox: cc.Node = null;

    @property({ type: cc.Prefab, tooltip: '客人item' })
    guestItem: cc.Prefab = null;

    @property({ type: cc.Prefab, tooltip: '收益item' })
    numItem: cc.Prefab = null;

    @property({ type: cc.Node, tooltip: '收益盒子' })
    numBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: '售卖收益' })
    rewardNumNode: cc.Node = null;

    @property({ type: cc.Node, tooltip: '金币堆' })
    rewardIcon: cc.Node = null;


    @property({ tooltip: '自动售卖摊位数' })
    _vendorMaxNum: number = 9;

    @property({ tooltip: '自动售卖菜篮子数' })
    _targetMaxNum: number = 3;

    @property({ tooltip: '自动售卖客人数' })
    _guestMaxNum: number = 3;

    @property({ tooltip: '自动售卖菜摊数据列表' })
    _autoVendorList: any[] = [];

    @property({ tooltip: '自动售卖菜篮数据列表' })
    _autoTargetList: any[] = [];

    @property({ tooltip: '运行帧数' })
    _dtNum: number = 0;

    @property({ tooltip: '累计时间' })
    _totalTime: number = 0;

    @property({ tooltip: '售卖收益动画' })
    _rewardSkeleton: sp.Skeleton = null;

    @property({ tooltip: '店主动画' })
    _bossSkeleton: any = null;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this._totalTime = 0;
        this.vendorUIItem.opacity = 0;
        UtilsModule_blxf.instance.setNodeSize_blxf( this.node );
    }

    start () {
        let { maxAutoVendorNum, maxAutoTargetNum } = ConfigModule_blxf;
        this._vendorMaxNum = maxAutoVendorNum;
        this._targetMaxNum = maxAutoTargetNum;

        this.updateUI_blxf();
        this.initEvent_blxf();
        this.initData_blxf();

        this.updateNode_blxf();

        this.loadGameNumPanel_blxf();
    }

    update ( dt: number ) {
        this._dtNum += 1;
        if ( this._dtNum < 60 ) return;

        
        this.updateDoubleTime_blxf( dt );

        this._dtNum % 10 == 1 && this.updateSaleRewardBtn_blxf();

        let _loadState: number = 0;

        _loadState = this.loadTargetList_blxf();
        if ( _loadState != -1 ) return;

        _loadState = this.loadVendorUIList_blxf();
        if ( _loadState != -1 ) return;

        _loadState = this.loadGuestList_blxf();
        if ( _loadState != -1 ) return;

        this.loadSpine_blxf();
    }

    initEvent_blxf () {
        cc.game.on('updateVendorUIItem_blxf', this.updateVendorUIItem_blxf, this);
        cc.game.on('updateTargetUIItem_blxf', this.updateTargetUIItem_blxf, this);
        cc.game.on('updateSaleRewardNum_blxf', this.updateSaleRewardNum_blxf, this);
        
        cc.game.on('loadGoldAnimation_blxf', this.loadGoldAnimation_blxf, this);
        cc.game.on('loadAutoNumItem_blxf', this.loadAutoNumItem_blxf, this);

        cc.game.on('onAutoCheckTargetLvUp_blxf', this.onAutoCheckTargetLvUp_blxf, this);
    }

    initData_blxf () {
        this.onAutoVendorData_blxf();

        this.onAutoTargetData_blxf();

        this.updateSaleRewardNum_blxf();
    }

    updateUI_blxf () {
        let _isHant = UtilsModule_blxf.instance.isTraditionalChinese_blxf();
        let _name: string = _isHant ? '杂货铺' : '小卖部';
        let _nameArr: string[] = _name.split('');
        this.nameBox.children.forEach( (textItem, index) =>{
            UtilsModule_blxf.setText_blxf( textItem, _nameArr[ index ] );
        })
    }

    /** 加载货币栏 */
    loadGameNumPanel_blxf () {
        PageManager_blxf.instance.loadGameNumPanel_blxf( 2, this.uiBox );
    }

    /** 更新收益显隐 */
    updateSaleRewardBtn_blxf () {
        let _rewardNum: number = GameData_blxf.instance.getAutoSaleRewardNum_blxf();
        let _isReward: boolean = _rewardNum > 0;
        this.rewardIcon.opacity = _isReward ? 255 : 0;
    }

    /** 更新售卖收益 */
    updateSaleRewardNum_blxf () {
        let _rewardNum: number = GameData_blxf.instance.getAutoSaleRewardNum_blxf();
        UtilsModule_blxf.setText_blxf( this.rewardNumNode, `${_rewardNum}` );

        _rewardNum > 0 && this.loadAutoSaleRewardSpine_blxf();
    }

    /** 自动售卖菜摊数据 */
    onAutoVendorData_blxf () {
        this._autoVendorList = [];
        
        let _vendorId: number;
        for ( _vendorId = 1 ; _vendorId <= this._vendorMaxNum ; _vendorId++ ) {
            let _data = CsvManager_blxf.instance.getVendorAndTargetData_blxf( 1, _vendorId );
            this._autoVendorList.push( _data[0] );
        }

        let _state = 0;
        this._autoVendorList.forEach( item =>{
            let { _isUnlock } = item;

            if ( _isUnlock ) return;

            item._unlockState = 0;
            if ( _state == 0 ) {
                _state = 1;
                item._unlockState = 1;
            }
        })
    }

    /** 自动售卖菜篮数据 */
    onAutoTargetData_blxf () {
        this._autoTargetList = [];
        this._guestMaxNum = 0;

        let _cfgTargetName = EnumManager_blxf.instance.getGameCsvType().CSV_TARGET;
        let _cfgTargetData = CsvManager_blxf.instance.getCsvDataByName_blxf( _cfgTargetName );

        let _cfgDataList: any[] = CsvManager_blxf.instance.getVendorAndTargetData_blxf( 2 );
        _cfgDataList.forEach( (item, targetIndex) =>{
            let { _isUnlock, checkType, checkNum } = item;
            let cfgTargetData: object = _cfgTargetData[ targetIndex + 1 ];
            cfgTargetData['UnlockType'] = checkType;
            cfgTargetData['UnlockNum'] = checkNum;
            let _autoData: object = { isAuto: true, autoTargetData: item };
            let baseTargetData: object = { isUnlock: _isUnlock, buyShopId: 1, buyShopNum: 10, ...cfgTargetData, ..._autoData };
            let targetData: BaseTargetData_blxf = new BaseTargetData_blxf( baseTargetData );

            this._autoTargetList.push( targetData );

            if ( _isUnlock ) this._guestMaxNum += 1;
        })
    }

    /** ui节点适配 */
    updateNode_blxf () {
        let { checkH } = ConfigModule_blxf.instance;
        this.uiBox.children.forEach( item =>{
            let _dir = item.y > 0 ? 1 : -1;
            item.y += checkH * _dir;
        })

        this.vendorBox.y -= checkH;
        this.targetBox.y -= checkH;
        this.guestBox.y -= checkH;

        let { isIpad, winSizeW } = ConfigModule_blxf.instance;
        if ( isIpad ) {
            this.uiBox.width = winSizeW;
            this.bgNode.width = winSizeW;
        }
    }

    /** 加载摊位UI_列表 */
    loadVendorUIList_blxf () {
        let _loadLen: number = this.vendorUIBox.childrenCount;
        let _isLoadOk: boolean = _loadLen >= this._vendorMaxNum;
        if ( _isLoadOk ) return -1;
        !_isLoadOk && this.loadVendorUIItem_blxf( _loadLen );
    }

    /** 加载摊位UI_item */
    loadVendorUIItem_blxf ( index: number ) {
        let _vendorUIItem = LoadModule_blxf.instance.LoadNode_blxf({
            prefabNode: this.vendorUIItem,
            parentNode: this.vendorUIBox
        })
        _vendorUIItem.opacity = 255;

        let _data = this._autoVendorList[ index ];
        let _autoVendorItem = LoadModule_blxf.instance.LoadNode_blxf({
            prefabNode: this.vendorItem,
            parentNode: this.vendorBox
        })
        let _itemThis = _autoVendorItem.getComponent(AutoVendorItem_blxf);
        _itemThis && _itemThis.initData_blxf && _itemThis.initData_blxf( _data );

        _autoVendorItem.on('touchend', this.onTouchAutoVendor_blxf.bind(this, _data));
    }

    /** 点击菜摊 */
    onTouchAutoVendor_blxf ( data: any ) {
        AudioModule_blxf.playTouchAudio_blxf();
        let { _isUnlock } = data;
        cc.game.emit('onTouchAutoPlayerBtn', null, _isUnlock ? '31' : '11');
    }

    /** 加载菜篮子列表 */
    loadTargetList_blxf () {
        let _loadNum: number = this.targetBox.childrenCount;
        let _isLoadOk: boolean = _loadNum >= this._targetMaxNum + 1;
        if ( _isLoadOk ) return -1;
        !_isLoadOk && this.loadTargetItem_blxf( _loadNum - 1 );
    }

    /** 加载菜篮子item */
    loadTargetItem_blxf ( index: number ) {
        let _targetData: BaseTargetData_blxf = this._autoTargetList[ [ 1, 0, 2][ index ] ];

        let _targetItem = LoadModule_blxf.instance.LoadNode_blxf({
            prefabNode: this.targetItem,
            parentNode: this.targetBox
        })

        let _targetItemThis = _targetItem.getComponent(TargetItem_blxf);
        _targetItemThis && _targetItemThis.initData_blxf && _targetItemThis.initData_blxf( _targetData );

        _targetItem.on('touchend', this.onTouchAutoTarget_blxf.bind(this, _targetData));
    }

    /** 点击菜篮 */
    onTouchAutoTarget_blxf ( data: any ) {
        cc.game.emit('onTouchAutoPlayerBtn', null, '11');
    }

    /** 加载客人列表 */
    loadGuestList_blxf () {
        let _loadNum: number = this.guestBox.childrenCount;
        let _isLoadOk: boolean = _loadNum >= this._guestMaxNum;
        if ( _isLoadOk ) return -1;
        !_isLoadOk && this.loadGuestItem_blxf( _loadNum );
    }

    /** 加载客人item */
    loadGuestItem_blxf ( index: number) {
        let _targetId: number = [ 2, 1, 3 ][ index ];
        let _x: number = [ 250, 50, 450 ][ index ];
        let _guestNode: cc.Node = LoadModule_blxf.instance.LoadNode_blxf({
            prefabNode: this.guestItem, parentNode: this.guestBox, position: cc.v2( _x, 0)
        })
        if ( !_guestNode ) return;

        let guestId: number = 1 + Math.ceil(Math.random() * 10);
        let _guestThis = _guestNode.getComponent( GuestItem_blxf );
        _guestThis.initData_blxf({ guestId, guestTargetId: _targetId });

        _guestThis.onCheckGuest_blxf( -1, false, false );
    }



    /** 更新菜摊UI */
    updateVendorUIItem_blxf ( vendorId: number ) {
        // 刷新数据
        this.initData_blxf();

        this.vendorBox.children.forEach( vendorItem =>{
            let _vendorItemThis = vendorItem.getComponent(AutoVendorItem_blxf);
            if ( !_vendorItemThis ) return;

            let _itemVendorId: number = _vendorItemThis.getVendorId_blxf();
            let _data: any = this._autoVendorList.find( item => item.ID == _itemVendorId );
            _vendorItemThis.initData_blxf( _data );
        })
    }

    /** 更新菜篮UI */
    updateTargetUIItem_blxf ( targetId: number = -1 ) {
        this.initData_blxf();

        this.targetBox.children.forEach( targetItem =>{
            let _targetItemThis = targetItem.getComponent(TargetItem_blxf);
            if ( !_targetItemThis ) return;

            let _itemTargetId: number = _targetItemThis.getTargetId_blxf();
            let _data: BaseTargetData_blxf = this._autoTargetList.find( item => {
                return item.targetId == _itemTargetId;
            });
            _targetItemThis.initData_blxf( _data );

            let _isLvUp: boolean = targetId == _itemTargetId;
            _isLvUp && PageManager_blxf.instance.loadSpineTargetLvUp_blxf( 
                targetItem, 0,
                ( spineSkeleton: sp.Skeleton, duration: number )=>{

            });
        })
    }

    /** 自动售卖菜摊上货 */
    addVendorShop_blxf ( vendorId: number, shopId: number ) {
        let _vendorItem: cc.Node = this.vendorBox.children.find( item =>{
            
        })

        this.vendorBox.children.forEach( item =>{
            let _vendorItemThis = item.getComponent(AutoVendorItem_blxf);
            if ( !_vendorItemThis ) return;
            
            let _itemVendorId: number = _vendorItemThis.getVendorId_blxf();
            if ( _itemVendorId != vendorId ) return;

            // todo 上货

        })
    }

    /** 点击领取奖励 */
    onTouchReceive () {
        let _rewardNum: number = GameData_blxf.instance.getAutoSaleRewardNum_blxf();
        if ( _rewardNum <= 0 ) return;

        AudioModule_blxf.instance.playAudio_blxf( EnumManager_blxf.gameAudioType.AUDIO_GOLD );

        let _inP: cc.Vec3 = UtilsModule_blxf.instance.getCanvasPos_blxf( this.numBox, this.numBox.position );
        NumModule_blxf.instance.updateNumByType( 1, _rewardNum, _inP );

        GameData_blxf.instance.setAutoSaleRewardNum_blxf( -_rewardNum );

        this._rewardSkeleton && this._rewardSkeleton.node.destroy();
        this._rewardSkeleton = null;

        this.updateSaleRewardNum_blxf();
    }

    /** 加载金币动画 */
    loadGoldAnimation_blxf ( position: cc.Vec3 ) {
        let _isDoubleSpeedTime: boolean  = UtilsModule_blxf.isDoubleSpeedTime_blxf();
        let _isDoubleRewardTime: boolean = UtilsModule_blxf.isDoubleRewardTime_blxf();
        let _iconNum: number = 1;
        if ( _isDoubleSpeedTime || _isDoubleRewardTime ) _iconNum = 3;
        if ( _isDoubleSpeedTime && _isDoubleRewardTime ) _iconNum = 6;

        let _toP: cc.Vec3 = UtilsModule_blxf.instance.getCanvasPos_blxf( this.numBox );
        PageManager_blxf.instance.onIconAnimation_blxf( -1, _iconNum, position, _toP, this.node );
    }

    /** 加载收益动画 */
    loadAutoNumItem_blxf ( data: any ) {
        let { x, y, isGuest } = data;
        let _x: number = 50 - Math.random() * 100, _y: number = 70;
        if ( isGuest ) _x = x, _y = y;
        let _parentNode = isGuest ? null : this.numBox;
        let _numItem = LoadModule_blxf.instance.LoadNode_blxf({
            prefabNode: this.numItem, parentNode: _parentNode, position: cc.v2(_x, _y), zIndex: 2000
        })

        let _numItemThis = _numItem.getComponent(AutoNumItem_blxf);
        _numItemThis && _numItemThis.initData_blxf && _numItemThis.initData_blxf( data );
    }

    // 客人：购买起始时间、购买物品
    // 菜篮：售卖物品
    // 地摊：物品列表

    // 数据 > 驱动 > UI
    // 重写 or 通用
    // 菜篮、客人、菜摊

    // 界面展示：客人持续购买、菜摊物品持续减少、菜篮物品持续更新
    // 购买表现：倒计时自动购买



    /**
     * 更新双倍增益时间
     * @param dt 当帧时间
     */
    updateDoubleTime_blxf ( dt: number ) {
        this._totalTime += dt;

        let _checkTime: number = 1;
        if ( this._totalTime < _checkTime ) return;

        this._totalTime -= _checkTime;

        UtilsModule_blxf.isDoubleRewardTime_blxf() && GameData_blxf.instance.updateAutoDoubleRewardTime_blxf( -_checkTime );
        UtilsModule_blxf.isDoubleSpeedTime_blxf() && GameData_blxf.instance.updateAutoDoubleSpeedTime_blxf( -_checkTime );
    }

    /** 加载售卖收益动画 */
    loadAutoSaleRewardSpine_blxf () {
        if ( this._rewardSkeleton ) return;
        let { SPINE_AUTO_REWARD } = EnumManager_blxf.gameSpineType;
        UtilsModule_blxf.instance.createSpine_blxf( SPINE_AUTO_REWARD, this.numBox, ( skeleton: sp.Skeleton )=>{
            this._rewardSkeleton = skeleton;
        });
    }


    /** 加载店主动画 */
    loadSpine_blxf () {
        if ( this._bossSkeleton ) return;
        this._bossSkeleton = true;

        let { SPINE_AUTO_BOSS } = EnumManager_blxf.gameSpineType;
        UtilsModule_blxf.instance.createSpine_blxf( SPINE_AUTO_BOSS, this.node, ( skeleton: sp.Skeleton )=>{
            this._bossSkeleton = skeleton;

            skeleton.node.y -= ConfigModule_blxf.instance.checkH;

            this.onPlayBossAnimation_blxf();
        });
    }

    /** 循环播放动画（喝水、呼吸） */
    onPlayBossAnimation_blxf () {
        let _name1: string = 'breath';
        let _name2: string = 'heshui';
        let _t: number = NumModule_blxf.instance.onAnimationTime_blxf( this._bossSkeleton, _name1 );
        let _t1: number = _t * (3 + Math.floor( Math.random() * 3 ));
        let _t2: number = NumModule_blxf.instance.onAnimationTime_blxf( this._bossSkeleton, _name2 );
        cc.tween( this._bossSkeleton.node )
        .delay( _t1 )
        .call(()=>{
            this.loadBossAnimation_blxf( _name2 );
        })
        .delay( _t2 )
        .call(()=>{
            this.loadBossAnimation_blxf( _name1 );

            this.onPlayBossAnimation_blxf();
        })
        .start();
    }

    // 播放店主动画
    loadBossAnimation_blxf ( name: string ) {
        UtilsModule_blxf.instance.palyAnimation_blxf( this._bossSkeleton, {
            animationName: name, isAlpha: true
        })
    }


    /** 检测自动售卖菜篮升级 */
    onAutoCheckTargetLvUp_blxf () {
        this.targetBox.children.forEach( targetItem =>{
            let _targetThis = targetItem.getComponent(TargetItem_blxf);
            if ( !_targetThis ) return;

            let _targetLv: number = _targetThis.getTargetLv_blxf();

            _targetThis.initTargetLvUpData_blxf();

            let _targetLv2: number = _targetThis.getTargetLv_blxf();
            if ( _targetLv == _targetLv2 ) return;

            // 加载升级动画
            PageManager_blxf.instance.loadSpineTargetLvUp_blxf( 
                targetItem, 0,
                ( spineSkeleton: sp.Skeleton, duration: number )=>{
                    // 升级音效
                    AudioModule_blxf.instance.playAudio_blxf( EnumManager_blxf.gameAudioType.AUDIO_DRAGON_EXP );
            });

            _targetThis.updateBgImg_blxf();
        })

        this.onAutoCheckVendorLvUp_blxf();
    }

    /** 检测自动售卖菜摊升级 */
    onAutoCheckVendorLvUp_blxf () {
        this.onAutoVendorData_blxf();

        this.vendorBox.children.forEach( (vendorItem, index) =>{
            let _vendorThis = vendorItem.getComponent( AutoVendorItem_blxf );
            if ( !_vendorThis ) return;

            let _vendorLv: number = _vendorThis.getVendorLv_blxf();
            if ( !_vendorLv ) return;

            let _data = this._autoVendorList[ index ];
            _vendorThis.initData_blxf( _data );

            let _vendorLv2: number = _vendorThis.getVendorLv_blxf();
            if ( _vendorLv == _vendorLv2 ) return;

            // 加载升级动画
            PageManager_blxf.instance.loadSpineTargetLvUp_blxf( 
                vendorItem, 0,
                ( spineSkeleton: sp.Skeleton, duration: number )=>{
                    // 升级音效
                    AudioModule_blxf.instance.playAudio_blxf( EnumManager_blxf.gameAudioType.AUDIO_DRAGON_EXP );
            });

        })
    }

}
